<template>
  <div class="user-management">
    <!-- 头部 -->
    <div class="header">
      <div class="header-left">
        <i class="fas fa-arrow-left" @click="goBack"></i>
        <h3>用户管理</h3>
      </div>
      <div class="header-right">
        <button class="btn primary-btn" @click="toAddUser">
          <i class="fas fa-user-plus"></i>
          新增用户
        </button>
        <button class="btn primary-btn" @click="toAddPerson">
          <i class="fas fa-user-edit"></i>
          新增自然人
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filters">
      <div class="search-box">
        <i class="fas fa-search"></i>
        <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索用户名、邮箱或手机号"
            @input="handleSearch"
        >
      </div>
      <div class="filter-group">
        <select v-model="filterStatus" @change="handleFilter">
          <option value="">全部状态</option>
          <option value="true">已激活</option>
          <option value="false">已禁用</option>
        </select>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-list">
      <div class="table-container">
        <table class="user-table">
          <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>手机号</th>
            <th>状态</th>
            <th>注册时间</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="user in filteredUsers" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ getPersonEmail(user) || '-' }}</td>
            <td>{{ getPersonPhone(user) || '-' }}</td>
            <td>
                <span :class="['status', user.activated ? 'inactive' : 'active']">
                  {{ user.activated ? '已禁用' :  '已激活'}}
                </span>
            </td>
            <td>{{ formatDate(user.createTime) }}</td>
            <td>
              <div class="actions">
                <button
                    class="btn action-btn"
                    @click="toggleUserStatus(user)"
                    :class="user.activated ? 'success' : 'danger'"
                >
                  {{ user.activated ? '启用' : '禁用'}}
                </button>
                <button
                    class="btn action-btn danger"
                    @click="deleteUser(user)"
                    v-if="user.id !== currentUserId && !isAdminUser(user)"
                >
                  删除
                </button>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-if="users.length === 0 && !loading">
        <i class="fas fa-users"></i>
        <p>暂无用户数据</p>
      </div>

      <!-- 加载状态 -->
      <div class="loading" v-if="loading">
        <i class="fas fa-spinner fa-spin"></i>
        <p>加载中...</p>
      </div>
    </div>

    <!-- 新增用户对话框 -->
    <div class="modal" v-if="showAddUserModal">
      <div class="modal-content">
        <div class="modal-header">
          <h4>{{ isAddPerson ? '新增自然人' : '新增用户' }}</h4>
          <i class="fas fa-times" @click="closeModal"></i>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitUser">
            <div class="form-group">
              <label>用户名 <span class="required">*</span></label>
              <input type="text" v-model="newUser.username" required placeholder="请输入用户名">
            </div>

            <template v-if="isAddPerson">
              <div class="form-group">
                <label>姓 <span class="required">*</span></label>
                <input type="text" v-model="newUser.lastName" placeholder="请输入姓" required>
              </div>

              <div class="form-group">
                <label>名 <span class="required">*</span></label>
                <input type="text" v-model="newUser.firstName" placeholder="请输入名" required>
              </div>

              <div class="form-group">
                <label>邮箱</label>
                <input type="email" v-model="newUser.email" placeholder="请输入邮箱">
              </div>

              <div class="form-group">
                <label>手机号</label>
                <input type="tel" v-model="newUser.phone" placeholder="请输入手机号">
              </div>

              <div class="form-group">
                <label>性别</label>
                <select v-model="newUser.gender">
                  <option value="">请选择性别</option>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </select>
              </div>
            </template>

            <div class="form-actions">
              <button type="button" class="btn cancel-btn" @click="closeModal">取消</button>
              <button type="submit" class="btn submit-btn" :disabled="submitting">
                {{ submitting ? '提交中...' : '提交' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { userAPI } from '@/api/user.js'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const users = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const filterStatus = ref('')
const currentUserId = ref(null)
const showAddUserModal = ref(false)
const isAddPerson = ref(false)
const submitting = ref(false)

const newUser = ref({
  username: '',
  firstName: '',
  lastName: '',
  email: '',
  phone: '',
  gender: ''
})

// 计算属性：筛选后的用户列表
const filteredUsers = computed(() => {
  let filtered = users.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(user =>
        user.username.toLowerCase().includes(keyword) ||
        (user.email && user.email.toLowerCase().includes(keyword)) ||
        (user.phone && user.phone.includes(keyword)) ||
        (user.firstName && user.firstName.toLowerCase().includes(keyword)) ||
        (user.lastName && user.lastName.toLowerCase().includes(keyword))
    )
  }

  // 状态筛选
  if (filterStatus.value) {
    filtered = filtered.filter(user => user.activated.toString() === filterStatus.value)
  }

  return filtered
})

// 页面加载时获取用户列表
onMounted(async () => {
  await loadUsers()
  await getCurrentUser()
})

// 获取当前用户ID
const getCurrentUser = async () => {
  try {
    const response = await userAPI.getActualUser()
    if (response.data) {
      currentUserId.value = response.data.id
    }
  } catch (error) {
    console.error('获取当前用户信息失败:', error)
  }
}

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  try {
    const response = await userAPI.getUsers()
    if (response.data && response.data.success === true && response.data.data) {
      users.value = response.data.data
    } else if (response.data) {
      users.value = response.data
    }
    console.log('用户列表:', users.value)
  } catch (error) {
    console.error('获取用户列表失败:', error)
    alert('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取Person对象的邮箱
const getPersonEmail = (user) => {
  return user.email || (user.personDetails && user.personDetails.email)
}

// 获取Person对象的手机号
const getPersonPhone = (user) => {
  return user.phone || (user.personDetails && user.personDetails.phone)
}

// 检查是否是管理员用户
const isAdminUser = (user) => {
  return user.authorities && user.authorities.some(auth => auth.name === 'ADMIN')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 打开新增用户对话框
const toAddUser = () => {
  isAddPerson.value = false
  resetNewUser()
  showAddUserModal.value = true
}

// 打开新增自然人对话框
const toAddPerson = () => {
  isAddPerson.value = true
  resetNewUser()
  showAddUserModal.value = true
}

// 重置新用户表单
const resetNewUser = () => {
  newUser.value = {
    username: '',
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    gender: ''
  }
}

// 关闭对话框
const closeModal = () => {
  showAddUserModal.value = false
  submitting.value = false
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

// 筛选处理
const handleFilter = () => {
  // 筛选逻辑已通过计算属性实现
}

// 提交用户
const submitUser = async () => {
  if (!newUser.value.username.trim()) {
    alert('请输入用户名')
    return
  }

  if (isAddPerson.value && (!newUser.value.firstName.trim() || !newUser.value.lastName.trim())) {
    alert('请输入完整的姓名')
    return
  }

  submitting.value = true
  try {
    let response

    if (isAddPerson.value) {
      // 新增自然人
      const personData = {
        username: newUser.value.username,
        firstName: newUser.value.firstName,
        lastName: newUser.value.lastName,
        email: newUser.value.email,
        phone: newUser.value.phone,
        gender: newUser.value.gender
      }
      console.log('提交自然人数据:', personData)
      response = await userAPI.addPerson(personData)
    } else {
      // 新增普通用户
      const userData = {
        username: newUser.value.username
      }
      console.log('提交用户数据:', userData)
      response = await userAPI.createUser(userData)
    }

    console.log('新增用户响应:', response)
    alert('用户添加成功')
    closeModal()
    await loadUsers() // 重新加载用户列表
  } catch (error) {
    console.error('添加用户失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '添加用户失败'
    alert('添加失败：' + errorMessage)
  } finally {
    submitting.value = false
  }
}

// 切换用户状态
const toggleUserStatus = async (user) => {
  const newStatus = !user.activated
  const action = newStatus ? '启用' : '禁用'

  if (!confirm(`确定要${action}用户 "${user.username}" 吗？`)) {
    return
  }

  try {
    // 调用启用/禁用接口
    await userAPI.toggleUserActivation(user.id, newStatus)
    user.activated = newStatus
    alert(`用户${action}成功`)
  } catch (error) {
    console.error(`${action}用户失败:`, error)
    const errorMessage = error.response?.data?.message || error.message || `${action}用户失败`
    alert(`${action}失败：${errorMessage}`)
  }
}

// 删除用户
const deleteUser = async (user) => {
  if (!confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复！`)) {
    return
  }

  if (user.id === currentUserId.value) {
    alert('不能删除当前登录的用户')
    return
  }

  if (isAdminUser(user)) {
    alert('不能删除管理员用户')
    return
  }

  try {
    // 调用删除用户接口
    await userAPI.deleteUser(user.id)
    users.value = users.value.filter(u => u.id !== user.id)
    alert('用户删除成功')
  } catch (error) {
    console.error('删除用户失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '删除用户失败'
    alert('删除失败：' + errorMessage)
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.user-management {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left i {
  font-size: 20px;
  color: #666;
  cursor: pointer;
}

.header-left h3 {
  margin: 0;
  color: #333;
}

.header-right {
  display: flex;
  gap: 10px;
}

.filters {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  background: white;
  padding: 15px;
  border-radius: 10px;
}

.search-box {
  position: relative;
  flex: 1;
}

.search-box i {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.search-box input {
  width: 100%;
  padding: 10px 10px 10px 35px;
  border: 1px solid #ddd;
  border-radius: 5px;
  outline: none;
}

.filter-group select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  outline: none;
}

.user-list {
  background: white;
  border-radius: 10px;
  overflow: hidden;
}

.table-container {
  overflow-x: auto;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th,
.user-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.user-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status.active {
  background: #d4edda;
  color: #155724;
}

.status.inactive {
  background: #f8d7da;
  color: #721c24;
}

.actions {
  display: flex;
  gap: 5px;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.primary-btn {
  background: #ee5a24;
  color: white;
}

.action-btn {
  background: #6c757d;
  color: white;
}

.action-btn.success {
  background: #28a745;
}

.action-btn.danger {
  background: #dc3545;
}

.empty-state,
.loading {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-state i,
.loading i {
  font-size: 48px;
  margin-bottom: 10px;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 10px;
  width: 500px;
  max-width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h4 {
  margin: 0;
}

.modal-header i {
  font-size: 20px;
  color: #999;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.required {
  color: #ff4757;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  outline: none;
}

.name-fields {
  display: flex;
  gap: 10px;
}

.name-fields input {
  flex: 1;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-btn {
  background: #6c757d;
  color: white;
}

.submit-btn {
  background: #ee5a24;
  color: white;
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
  }

  .filters {
    flex-direction: column;
  }

  .actions {
    flex-direction: column;
  }

  .name-fields {
    flex-direction: column;
  }
}
</style>